package com.sun.temp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.temp.bean.Material;
import com.sun.temp.bean.Task;
import com.sun.temp.common.result.PageResult;
import com.sun.temp.mapper.mapper1.TaskDao;
import com.sun.temp.service.MaterialService;
import com.sun.temp.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class TaskServiceImpl extends ServiceImpl<TaskDao, Task> implements TaskService {

    @Resource
    private TaskDao taskDao;

    @Autowired
    private MaterialService materialService;

    @Override
    public List<Task> queryAllTask() {
        return this.baseMapper.queryAllTask();
    }

    @Override
    public Page<Task> queryPage(Map<String, Object> params) {
        String pageNum = (String)params.get("page");
        String status = (String)params.get("status");
        String startTime = (String)params.get("startTime");
        String endTime = (String)params.get("endTime");

        Page<Task> page = this.page(
                new Page<>(Integer.valueOf(pageNum),10),
                new QueryWrapper<Task>()
//                        .eq("status", status)
                        .orderByDesc("create_time")
                        .eq(StringUtils.isNotBlank(status),"status", status)
                        .gt(StringUtils.isNotEmpty(startTime),"create_time",startTime+" 00:00:00")
                        .lt(StringUtils.isNotEmpty(endTime),"create_time",endTime+" 23:59:59")
        );
        List<Task> records = page.getRecords();
        for (Task entity : records) {
            // 获取批次
            List<Material> list = materialService.queryBatchByTaskId(entity.getId());
            List<Material> succesList = materialService.queryBatchSuccessByTaskId(entity.getId());
            entity.setBatchCount(list.size());
            entity.setSuccessCount(succesList.size());
        }

        return page;
    }

    @Override
    public List<Task> queryTaskToday() {
        return this.baseMapper.queryTaskToday();
    }

    @Override
    public void insertTask(Task task) {
        taskDao.insert(task);
    }

}
